<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyWord" placeholder="部门名称或者部门编号"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployees">用户名查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工用户名" width="120" sortable>
			</el-table-column>
			<el-table-column prop="email" label="员工邮箱" width="120" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="员工电话" width="120" sortable>
			</el-table-column>
			<el-table-column prop="age" label="员工年龄" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state==1" >启用</span>
					<span style="color: red" v-else-if="scope.row.state==0" >禁用</span>
					<span style="color: black" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门" width="100" sortable>
			</el-table-column>
			<el-table-column prop="shop.name" label="所属店铺" width="120" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <!-- @current-change="handleCurrentChange"绑定点击事件，这就是换页的操作 -->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面 -->

		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="editForm.password" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="editForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="editForm.age" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="所属部门" prop="department">
					<!-- 部门领导的下拉框 value-key="id"为传值是对象必须要加 ，clearable为可以删除的属性，-->
					<!-- v-model="editForm.manager"双向绑定，在下面value的中为双向绑定填的值，将选中的值传到该表单中在修改和添加的时候就可以将管理者这个对象传到后端中 -->
					<!-- key为唯一表示填的就是id -->
					<!-- lable 需要展示的值要是不设置就和value相同 -->
					<!-- value为传到后台的数据（传整个员工信息）也就是双向绑定v-model="editForm.manager"可以改变的值 -->
					<el-select v-model="editForm.department" value-key="id" clearable placeholder="请选择">
						<el-option
								v-for="item in departments"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name}}</span> <!-- 在前面的数据，和lable相同 -->
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn}}</span> <!-- 在后面的数据 -->
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所属店铺"  prop="shop">
					<!-- 部门领导的下拉框 value-key="id"为传值是对象必须要加 ，clearable为可以删除的属性，-->
					<!-- v-model="editForm.manager"双向绑定，在下面value的中为双向绑定填的值，将选中的值传到该表单中在修改和添加的时候就可以将管理者这个对象传到后端中 -->
					<!-- key为唯一表示填的就是id -->
					<!-- lable 需要展示的值要是不设置就和value相同 -->
					<!-- value为传到后台的数据（传整个员工信息）也就是双向绑定v-model="editForm.manager"可以改变的值 -->
					<el-select v-model="editForm.shop" value-key="id" clearable placeholder="请选择">
						<el-option
								v-for="item in shops"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name}}</span> <!-- 在前面的数据，和lable相同 -->
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.address}}</span> <!-- 在后面的数据 -->
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<!-- 单击提交调用方法editSubmit -->
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>


		</el-dialog>


	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyWord: ''
				},
				tree: [],
				employees: [], // 定义所有员工的集合
				title:"",
				departments: [],
				shops:[],
				total: 0,
                pageSize:5, // 每次调用getDepartment默认为查询5条数据
				currentPage: 1,// 每次调用getDepartment默认为第一页
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				// 必填项的校验
				editFormRules: {
				    /* 当鼠标光标的焦点从该框中移开的时候就会有提示 */
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入用户密码', trigger: 'blur' }
					],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ]
				},
				//编辑界面数据 ，初始值
				editForm: {
					id: null,
					username: '',
					password: '',
					email:'',
					age:'',
					phone:'',
					state: 1,
                    department: null,
                    shop: null
				},


			}
		},
		methods: {

			handleCurrentChange(val) {
				this.currentPage = val; // 获取当前点击的页数
				this.getEmployees(); // 调用方法执行高级查询
			},
			//获取部门列表，
			getDepartments() {
                this.$http.get("/dept")
                    .then(result=>{
                        this.departments = result.data;
                    }).catch(result=>{
                    alert("系统繁忙")
                })
			},
			// 获取店铺列表
			getShops() {
                this.$http.get("/shop")
                    .then(result=>{
                        this.shops = result.data;
                    }).catch(result=>{
                    alert("系统繁忙")
                })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					// 发送请求给后台接收
					this.$http.delete("/emp/"+row.id)
						.then(result=>{
                            this.listLoading = false; // 关闭忙等框
						    if(result.data.success){ // 删除成功的提示信息
                                this.$message({
									message: '删除成功',
									type: 'success'
								});
							}else {
                                this.$message({ // 删除失败的提示信息
									message: result.data.msg,
									type: 'error'
								});
							}
							this.currentPage=1;
						    this.getEmployees();
						}).catch(result=>{
							this.$message({
								message: '系统繁忙',
								type: 'error'
							});
						})
				}).catch(() => {

				});
                // let para = { id: row.id };
                // removeDepartment(para).then((res) => {
                //     this.listLoading = false;
                //     //NProgress.done();
                //     this.$message({
                //         message: '删除成功',
                //         type: 'success'
                //     });
                //     this.getDepartments();
                // });
			},
			// 鼠标单击编辑调用该方法，打开模态框，并且初始化模态框中的值，显示编辑界面，并且调用this.queryTree();方法查询部门树
			handleEdit: function (index, row) {
			    this.queryTree();
				this.editFormVisible = true;
                this.title="编辑";
                this.editForm = Object.assign({}, row); // 模态框回显页面
			},
			// 鼠标单击新增调用该方法，打开模态框，并且初始化模态框中的值，显示新增界面，并且调用this.queryTree();方法查询部门树
			handleAdd: function () {
			    this.queryTree();
				this.editFormVisible = true;
                this.title="新增";
                this.editForm = { // 设置新增界面的初始值，新增没有id
                    username: '',
                    password: '',
                    email:'',
                    age:'',
                    phone:'',
                    state: 1,
                    department: null,
                    shop: null
				};
			},
            //编辑和新增发送请求的方法
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '友情提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            /*if (para.parent){ // 判断para参数是否为空，不为空就执行操作将数组转化为json格式的数据，由于之前的parent是数组这样的话，后端无法接收，因为后端接收是对象所以是数组的话会报400的错误
                                let arr = para.parent;
                                let id = arr[arr.length-1];
                                para.parent = {"id":id};
                            }*/
							this.$http.put("/emp",para)
								.then(result=>{
                                    this.editLoading = false; // 关闭提交按钮的忙等框
                                    if (result.data.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
									}else {
                                        this.$message({
                                            message: result.data.msg,
                                            type: 'success'
                                        });
									}
                                    this.editFormVisible = false; // 关闭模态框
									this.currentPage=1;
									this.getEmployees()
								}).catch(result=>{

							})
							/*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    // 将点击的所有行的id提取出来放到数组中
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					/*let para = {"ids":ids}*/
                    // 发送的请求中的数据ids为数组
					this.$http.patch("/emp",ids)
						.then(result=>{
                            this.listLoading = false; // 关闭忙等框
							if (result.data.success){
                                this.$message({
									message: '删除成功',
									type: 'success'
								});
							}else {
                                this.$message({
                                    message: result.data.msg,
                                    type: 'error'
                                });
							}
							this.currentPage = 1;
							this.getEmployees();
						}).catch(result=>{
                        this.$message({
                            message: '系统错误',
                            type: 'error'
                        });
					})
				}).catch(() => {

				});
                // let para = { ids: ids };
                // batchRemoveDepartment(para).then((res) => {
                //     this.listLoading = false;
                //     //NProgress.done();
                //     this.$message({
                //         message: '删除成功',
                //         type: 'success'
                //     });
                //     this.getDepartments();
                // });
			},
			/*  */
            getEmployees() { // 定义方法发送请求，在后端将所有员工的信息都查出来
                let para = { // 高级查询需要的参数
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyWord: this.filters.keyWord
                };
                this.listLoading = true;
                this.$http.post("/emp",para)
                    .then(result=>{
                        console.debug(result)
                        this.employees = result.data.rows;
                        this.total = result.data.totals;
                        this.listLoading = false;
                    }).catch(result=>{
                    console.debug(result);
                    alert("系统繁忙")
                })
            },
			queryTree(){ /* 发送请求查询部门树 */
			    this.$http.get("/dept/tree")
					.then(result=>{
						this.tree = result.data;
						console.debug(this.tree)
					}).catch(result=>{

				})
			}
		},

		mounted() {
			this.getDepartments(); // 加载部门
			this.getEmployees(); // 在页面已加载之后就发送请求，查询所有员工的信息
			this.getShops();// 加载店铺
		}
	}

</script>

<style scoped>

</style>